package com.isale.service.impl;

import com.isale.model.db.SysUser;
import com.isale.dao.SysUserRepository;
import com.isale.service.SysUserService;

        import org.apache.commons.logging.Log;
        import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

        import java.util.ArrayList;
        import java.util.List;


/**
 * 
 * 数据库表【sys_user】对应的service实现类
 *
 * @author  bjs
 * @date 2016-11-22 15:18:06
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private static final Log logger = LogFactory.getLog(SysUserServiceImpl.class);

    @Autowired
    private SysUserRepository sysUserRepository;


    @PersistenceContext
    private EntityManager entityManager;


    //===================================================================================================

    /**
     * 保存或更新对象
     *
     * @param sysUser
     */
    @Override
    public void save(SysUser sysUser) {
        sysUserRepository.save(sysUser);
    }


    /**
         * 通过id查找对象
         *
         * @param id
         * @return
         */
    @Override
    public SysUser findById(Long id) {
        return sysUserRepository.findOne(id);
    }






    /**
    * 提供给管理使用的分页查询
    *
    * @param pageable
    * @return
    */
    @Override
    public Page<SysUser> findForAdminList(Pageable pageable) {
        StringBuffer sqlForCount = new StringBuffer("select count(c.id) from SysUser c where 1=1 ");
        StringBuffer sqlForList = new StringBuffer("select c from SysUser c where 1=1 ");

        /*
        if (StringUtils.isNotBlank(name)) {
            sqlForCount.append(" and ( c.name like  '%" + name + "%' or c.username like '%" + name + "%' )  ");
            sqlForList.append(" and ( c.name like  '%" + name + "%' or c.username like '%" + name + "%' )  ");
        }
        */

        sqlForList.append(" order by c.id desc ");

        TypedQuery queryForCount = entityManager.createQuery(sqlForCount.toString(), Long.class);
        Long count = (Long) queryForCount.getSingleResult();

        TypedQuery queryForList = entityManager.createQuery(sqlForList.toString(), SysUser.class);
        List<SysUser> adminList = queryForList.setMaxResults(pageable.getPageSize()).setFirstResult(pageable.getOffset()).getResultList();

        Page<SysUser> pageRst = new PageImpl<SysUser>(adminList, pageable, count);
        return pageRst;
    }



}
